package com.example.aidocengine.controller;

import com.example.aidocengine.common.result.ApiResponse;
import com.example.aidocengine.pojo.dto.response.ValidationResultResponse;
import com.example.aidocengine.pojo.entity.StartupPlanValidationStatistics;
import com.example.aidocengine.service.StartupPlanValidationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@RestController
@RequestMapping("/api/startup-plan")
public class StartupPlanValidationController {

    @Autowired
    private StartupPlanValidationService startupPlanValidationService;

    @PostMapping("/validate")
    public ApiResponse<ValidationResultResponse> validateStartupPlan(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "description", required = false) String description) {
        
        log.info("收到启动方案校验请求，文件名：{}", file.getOriginalFilename());
        
        ValidationResultResponse response = startupPlanValidationService.validateStartupPlan(file, description);
        return ApiResponse.success("校验完成", response);
    }

    @GetMapping("/result/{documentId}")
    public ApiResponse<ValidationResultResponse> getValidationResult(
            @PathVariable Long documentId) {
        
        ValidationResultResponse response = startupPlanValidationService.getValidationResult(documentId);
        return ApiResponse.success(response);
    }

    @GetMapping("/download/{documentId}")
    public ResponseEntity<Resource> downloadModifiedWordDocument(
            @PathVariable Long documentId) {
        
        log.info("收到下载修改后Word文档请求，文档ID：{}", documentId);
        
        try {
            // 生成修改后的Word文档
            byte[] modifiedDocument = startupPlanValidationService.generateModifiedWordDocument(documentId);
            
            ByteArrayResource resource = new ByteArrayResource(modifiedDocument);
            
            String filename = "启动方案校验结果_" + documentId + ".docx";
            
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
                    .contentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.wordprocessingml.document"))
                    .contentLength(modifiedDocument.length)
                    .body(resource);
                    
        } catch (Exception e) {
            log.error("下载修改后Word文档失败", e);
            // 返回错误响应
            byte[] errorData = "下载失败，请稍后重试".getBytes();
            ByteArrayResource errorResource = new ByteArrayResource(errorData);
            return ResponseEntity.internalServerError().body(errorResource);
        }
    }
    
    @GetMapping("/statistics")
    public ApiResponse<StartupPlanValidationStatistics> getLatestValidationStatistics() {
        log.info("收到获取最新校验统计数据请求");
        
        StartupPlanValidationStatistics statistics = startupPlanValidationService.getLatestValidationStatistics();
        return ApiResponse.success("获取成功", statistics);
    }
}